#!/usr/bin/env bash

help(){
    cat<<__EOF__
Usage: m dir [OPTIONS] [PATH]

Description:  Manage directories and files in the current or specified path.

Options:
  --delete  <empty|dsfiles>  Delete DS_Files files or empty folders recursively in the current path or a specified path.
  --dsfiles <enable|disable> Enable or disable the generation of .DS_Store files.
  --size                     Calculate the size of the current folder or a specified path.
  --tree                     Display a tree view of folders in the current path or a specified path.
__EOF__

}

confirm () {
    # call with a prompt string or use a default
    read -r -p "${1:-Are you sure? [y/n]} " response
    case $response in
        [yY][eE][sS]|[yY])
            true
            ;;
        *)
            false
            ;;
    esac
}

tree_dirs() {
    local dir="${1:-.}"

    [[ ! -d "$dir" ]] && echo "Directory ${dir} does not exist." >&2 && return

    local prefix="$2"

    local -a entries
    IFS=$'\n' read -rd '' -a entries <<< "$(ls -A "$dir" 2>/dev/null | sort)"

    local total=${#entries[@]}
    local i=1

    for name in "${entries[@]}"; do
        local connector="├──"
        [[ $i -eq $total ]] && connector="└──"

        echo "${prefix}${connector} $name"

        if [[ -d "$dir/$name" ]]; then
            local new_prefix="$prefix"
            [[ $i -eq $total ]] && new_prefix+="    " || new_prefix+="│   "
            tree_dirs "$dir/$name" "$new_prefix"
        fi
        ((i++))
    done
}

# delete empty folders
delete_empty(){
    DIRS="${@:-.}"
    echo "Folders to be deleted: "
    find "${DIRS}" -type d -empty -print
    confirm && find "${DIRS}" -type d -empty -delete
}

# delete .DS_Store files
delete_dsfiles(){
    DIRS="${@:-.}"
    echo "Files to be deleted: "
    find "${DIRS}" -type f -name .DS_Store -print
    confirm && find "${DIRS}" -type f -name .DS_Store -print -delete
}

folder_size(){
    dir="${@:-.}"
    echo "Folder size:"
    du -sh "${dir}"
}

delete(){
    case "$1" in
        empty)
            shift;
            delete_empty "$@"
            ;;
        dsfiles)
            shift;
            delete_dsfiles "$@"
            ;;
        *)
            help && exit 1
            ;;
    esac
}

dsfiles(){
    case "$1" in
        enable)
            defaults delete com.apple.desktopservices DSDontWriteNetworkStores
            echo ".DS_Store files enabled"
            ;;
        disable)
            defaults write com.apple.desktopservices DSDontWriteNetworkStores -bool TRUE
            echo ".DS_Store files disabled"
            ;;
        *)
            help && exit 1
            ;;
    esac
}


# Main script execution
option="${1}"
shift

case "${option}" in
    --help)
        help
        ;;
    --tree)
        tree_dirs "$@"
        ;;
    --delete)
        delete "$@"
        ;;
    --dsfiles)
        dsfiles "$@"
        ;;
    --size)
        folder_size "$@"
        ;;
    *)
        help && exit 1
        ;;
esac
